/*
 * @Author: Jimmy
 * @LastModifiedBy: Jimmy
 * @Date: 2024-05-12 11:26:07
 * @LastEditTime: 2024-09-04 21:41:52
 * @FilePath: /nest_study/server/src/common/filters/exceptions-filter.ts
 */
import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, Logger } from '@nestjs/common';

@Catch()
export class ExceptionsFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    const start = Date.now();
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const status = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
    const request = ctx.getRequest<Request>();  //  这里可以得到请求的绝大部分信息
    const reqHeaders: any = request.headers  //得到请求头信息
    const urlInfo = `${request.method} ${request.url}`;
    Logger.error(`请求接口: ${urlInfo}, 响应时间: ${Date.now() - start} ms 响应消息：${exception.message} 请求来源: ${reqHeaders.host}`)
    response.status(status).json({
      code: status,
      msg: `Service Error: ${exception}`,
    });
  }
}
